const ModelMusic = require('../../models/music'),
    ModelLyric = require('./musicLyric'),
    FileTool = require('../../utils/filetool'),
    ComTool = require('../../utils/commonTools');
const fs = require("fs"),
    multiparty = require('multiparty'),
    fse = require('fs-extra'),
    path = require('path');

const Msvafloder = 'music' + '/' + ComTool.getCurrentDay(),
    imgSavePath = "/images/musics_cover_src",
    upload_dir = './public/' + Msvafloder; //音乐文件的保存路径

let localParams = {};

// 是否禁用
exports.isLockMusic = (req, res, next) => {
    const {
        music_id,
        is_lock
    } = req.body;
    if (music_id && is_lock) {
        ModelMusic.updateMusic({
            is_lock
        }, {
            music_id
        }, (value) => {
            res.render('success', {
                data: JSON.stringify({
                    message: "更新成功",
                    status: 200,
                    affectedRows: value.affectedRows
                })
            })
        }, (error) => {
            res.render('fail', {
                data: JSON.stringify({
                    message: "更新失败",
                    status: 200,
                    error
                })
            })
        });
    }
}

// 编辑音乐
exports.updateMusic = async (req, res, next) => {
    const {
        data,
        _filename,
        _imgfile
    } = req.body;
    let fileImg = _imgfile ? await FileTool.saveImage(_imgfile, './public' + imgSavePath) : null;
    let file = _filename ? await MusicMerge(_filename) : null;

    if (fileImg === false) {
        return res.render('fail', {
            data: JSON.stringify({
                message: "图片保存失败",
                status: 200,
            })
        })
    } else if (file === false) {
        FileTool.removeFile('./public' + imgSavePath + '/' + fileImg.saveFloder + '/', fileImg.name);
        return res.render('fail', {
            data: JSON.stringify({
                message: "文件保存失败",
                status: 200,
            })
        })
    }
    if (fileImg !== null) {
        if (data.music_cover_src && data.music_cover_name)
            FileTool.removeFile('./public' + data.music_cover_src, data.music_cover_name);
    }
    if (file != null) {
        if (data.music_file_src && data.music_file_name)
            FileTool.removeFile('./public' + data.music_file_src, data.music_file_name);
    }

    let newData = {
        ...data,
        music_cover_name: fileImg ? fileImg.name : null,
        music_cover_src: fileImg ? imgSavePath + '/' + fileImg.saveFloder + '/' : null,
        music_file_src: file && file.filesrc,
        music_file_name: file && file.filename,
    }

    const {
        music_id
    } = newData;
    if (music_id) {
        delete newData.music_id;
        ModelMusic.updateMusic(newData, {
            music_id
        }, (value) => {
            res.render('success', {
                data: JSON.stringify({
                    message: "更新成功",
                    status: 200,
                    affectedRows: value.affectedRows
                })
            })
        }, (error) => {
            res.render('fail', {
                data: JSON.stringify({
                    message: "更新失败",
                    status: 200,
                    error
                })
            })
        });
    }
}

/** 添加音乐 */
exports.addMusic = async (req, res, next) => {
    const {
        data,
        _filename,
        _imgfile
    } = req.body;
    let fileImg = _imgfile ? await FileTool.saveImage(_imgfile, './public' + imgSavePath) : null;
    let file = _filename && await MusicMerge(_filename);
    if (fileImg === false) {
        FileTool.removeFile('./public' + file.filesrc, file.filename);
        return res.render('fail', {
            data: JSON.stringify({
                message: "图片保存失败",
                status: 200,
            })
        })
    } else if (file === false) {
        FileTool.removeFile('./public' + imgSavePath + '/' + fileImg.saveFloder + '/', fileImg.name);
        return res.render('fail', {
            data: JSON.stringify({
                message: "文件保存失败",
                status: 200,
            })
        })
    } else {
        if (data.music_cover_src && data.music_cover_name)
            FileTool.removeFile('./public' + data.music_cover_src, data.music_cover_name);
    }

    let newData = {
        ...data, //如果传入的参数文件名存在  覆盖图片文件名
        music_cover_name: fileImg ? fileImg.name : null,
        music_cover_src: fileImg ? imgSavePath + '/' + fileImg.saveFloder + '/' : null,
        music_file_name: file.filename,
        music_file_src: file.filesrc,
        music_id: ComTool.orderCode(),
    }

    ModelMusic.addMusic(
        newData,
        (value) => {
            res.render('success', {
                data: JSON.stringify({
                    message: "添加成功",
                    status: 200,
                    affectedRows: value.affectedRows
                })
            })
        }, (error) => {
            res.render('fail', {
                data: JSON.stringify({
                    message: "添加失败",
                    status: 200,
                    error
                })
            })
        });
}
/** 文件合并 */
const MusicMerge = async (filename) => {
    let name = filename;
    let fname = name.split(`.${localParams.suffix}`)[0];

    let chunkDir = upload_dir + "/" + fname;

    if (!fse.existsSync(chunkDir)) {
        console.log("文件分片路径不存在");
        return false;
    }
    let chunks = await fse.readdir(chunkDir);
    FileTool.removeFile(upload_dir + "/", name); // 假如出现相同的文件名
    chunks.sort((a, b) => a - b).map(chunkPath => {
        fs.appendFileSync(upload_dir + "/" + name,
            fs.readFileSync(`${chunkDir}/${chunkPath}`))
    })

    fse.removeSync(chunkDir);
    return {
        filename: name,
        filesrc: `/${Msvafloder}/`
    }
}

/**取消上传并删除整个分片文件夹 */
exports.cancelUpload = (req, res, next) => {
    if (localParams.currentMusicFiles) {
        try {
            FileTool.emptyFloder(localParams.currentMusicFiles);
            res.render('success', {
                data: JSON.stringify({
                    message: "取消上传",
                    status: 200,
                })
            })
        } catch (error) {
            res.render('fail', {
                data: JSON.stringify({
                    message: "取消失败",
                    status: 200,
                    error
                })
            })
        }
    }
}

/**文件分片 */
exports.addMusicFile = (req, res, next) => {
    const form = new multiparty.Form()
    form.parse(req, async function (err, fields, files) {
        const index = fields.index[0], // 文件分片编号
            suffix = fields.suffix[0], // 后缀
            chunk = files.file[0],
            fname = chunk.originalFilename.split(`.${suffix}`)[0];

        // 存放切片目录
        let chunkDir = `${upload_dir}/${fname}`
        if (!fse.existsSync(chunkDir)) {
            await fse.mkdirs(chunkDir);
        }
        // 原文件名.index.ext
        var dPath = path.join(chunkDir, index)
        await fse.move(chunk.path, dPath, {
            overwrite: true
        })
        localParams.currentMusicFiles = chunkDir;
        localParams.suffix = suffix;
        return res.render('success', {
            data: JSON.stringify({
                message: "文件上传成功",
                status: 200,
                value: {
                    music_name: fname.split('_')[0],
                    dirname: chunk.originalFilename
                }
            })
        })
    });
}

// 删除音乐
exports.delMusic = async (req, res, next) => {
    const {
        music_id,
        music_cover_name,
        music_cover_src,
        music_file_src,
        music_file_name,
        lyric_id,
        lyric_src,
        lyric_file_name
    } = req.body;
    ModelMusic.delMusic({
        music_id
    }, (value) => {
        FileTool.removeFile('./public' + music_cover_src, music_cover_name);
        FileTool.removeFile('./public' + music_file_src, music_file_name);
        // FileTool.removeFile(lyric_src, lyric_file_name);

        if (lyric_id, lyric_src, lyric_file_name)
            return ModelLyric.delMusicLyric({ // 删除歌词
                query: {
                    lyric_id
                }
            }, res)

        res.render('success', {
            data: JSON.stringify({
                message: "删除成功",
                status: 200,
                affectedRows: value.affectedRows
            })
        })
    }, (error) => {
        res.render('fail', {
            data: JSON.stringify({
                message: "删除失败",
                status: 200,
                error
            })
        })
    });
}
/** 查找根据字符串id查找多条音乐 */
exports.findMusicByids = async (req, res, next) => {
    const {
        ids
    } = req.body;
    let Music = await ModelMusic.findMusicByids(ids);
    Music.success((value) => {
        if (value.length) {
            res.render('success', {
                data: JSON.stringify({
                    message: "查找到音乐",
                    value: value,
                    status: 200,
                    length: value.length
                })
            })
        } else {
            res.render('fail', {
                data: JSON.stringify({
                    message: "没有找到音乐",
                    value: value,
                    length: value.length
                })
            })
        }
    });

    Music.fail((error) => {
        res.render('fail', {
            data: JSON.stringify({
                message: "查找失败",
                error
            })
        })
    })
}

/** 查找根据字符串name查找多条音乐 */
exports.findMusicByName = async (req, res, next) => {
    let Music = await ModelMusic.findMusicByName(req.body.name);
    Music.success((value) => {
        if (value.length) {
            res.render('success', {
                data: JSON.stringify({
                    message: "查找到音乐",
                    value: value,
                    status: 200,
                    length: value.length
                })
            })
        } else {
            res.render('fail', {
                data: JSON.stringify({
                    message: "没有找到音乐",
                    value: value,
                    length: value.length
                })
            })
        }
    });

    Music.fail((error) => {
        res.render('fail', {
            data: JSON.stringify({
                message: "查找失败",
                error
            })
        })
    })
}


//随机查找n首音乐
exports.findRand = (req, res, next) => {
    ModelMusic.findRand({
            limit: req.body.limit
        },
        (value) => {
            res.render('success', {
                data: JSON.stringify({
                    message: "查找成功",
                    status: 200,
                    value: value,
                    length: value.length
                })
            })
        }, (error) => {
            res.render('fail', {
                data: JSON.stringify({
                    message: "查找失败",
                    status: 200,
                    error
                })
            })
        });
}

/** 查找音乐 */
exports.findMusic = async (req, res, next) => {
    let Music = await ModelMusic.findMusic(req.body);
    Music.success((value) => {
        if (value.length) {
            res.render('success', {
                data: JSON.stringify({
                    message: "查找到音乐",
                    value: value,
                    status: 200,
                    length: value.length
                })
            })
        } else {
            res.render('fail', {
                data: JSON.stringify({
                    message: "没有找到音乐",
                    value: value,
                    length: value.length
                })
            })
        }
    });

    Music.fail((error) => {
        res.render('fail', {
            data: JSON.stringify({
                message: "查找失败",
                error
            })
        })
    })
}

//查找所有音乐
exports.list = async (req, res, next) => {
    ModelMusic.findAll(
        (value) => {
            res.render('success', {
                data: JSON.stringify({
                    message: "查找成功",
                    status: 200,
                    value: value,
                    length: value.length
                })
            })
        }, (error) => {
            res.render('fail', {
                data: JSON.stringify({
                    message: "查找失败",
                    status: 200,
                    error
                })
            })
        });
}